﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Customization;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Ribbon;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.Windows;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Serialization;

//在位块编辑，点击保存关闭
//导出图像后再导出块对象
//pu（-pu）资源清理，减小dwg文件大小
//laydel 删除图层
//XR外部参照管理
//attmode 0属性文字不显示
//pe选择多个直线转换多段线，x多段线转直线

[assembly: ExtensionApplication(typeof(AutoCadConvert.MenuConvert))]
namespace AutoCadConvert
{
    public class MenuConvert : IExtensionApplication
    {
        public void Initialize()
        {
            //设置可调式
#if DEBUG
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("NEXTFIBERWORLD", 0);
#endif

            ContextMenuExtension cm = new ContextMenuExtension();
            cm.Title = "四维聚象(AutoCad)";
            MenuItem mItem1 = new MenuItem("导出户型数据");
            mItem1.Click += MItem1_Click;
            MenuItem mItem2 = new MenuItem("创建默认图层");
            mItem2.Click += MItem2_Click;
            MenuItem mItem3 = new MenuItem("四维聚象工作平台");
            mItem3.Click += MItem3_Click;
            MenuItem mItem4 = new MenuItem("标记房间");
            mItem4.Click += MItem4_Click;
            MenuItem mItem5 = new MenuItem("账号登陆");
            mItem5.Click += MItem5_Click;
            MenuItem mItem6 = new MenuItem("注销账号");
            mItem6.Click += MItem6_Click;
            //添加右键菜单
            cm.MenuItems.Add(mItem5);
            cm.MenuItems.Add(mItem1);
            cm.MenuItems.Add(mItem3);
            cm.MenuItems.Add(mItem4);
            cm.MenuItems.Add(mItem2);
            cm.MenuItems.Add(mItem6);
            Autodesk.AutoCAD.ApplicationServices.Application.AddDefaultContextMenuExtension(cm);
            
            //LoginInfo.instance().isLogin = true;
        }
        private void MItem6_Click(object sender, EventArgs e)
        {//工作台
            DwgConvert.ChangeUser();
        }
        private void MItem5_Click(object sender, EventArgs e)
        {//工作台
            DwgConvert.Login("");
        }
        private void MItem4_Click(object sender, EventArgs e)
        {//工作台
            DwgConvert.CreateText();
        }
        private void MItem3_Click(object sender, EventArgs e)
        {//工作台
            DwgConvert.PaletteSetPopOut();
        }
        private void MItem2_Click(object sender, EventArgs e)
        {//图层
            DwgConvert.CreateDefaultLayer();
        }
        private void MItem1_Click(object sender, EventArgs e)
        {//导出
            DwgConvert.ExportBSPXml();
        }
        public void Terminate()
        {
            DwgConvert.Logout();
        }
    }
    public class DwgConvert
    {
        public static PaletteSet s_Ps=null;
        public static DwgItem s_DmCtrl=null;
        private static ProgressMeter s_Pmeter = new ProgressMeter();//进度条显示
        public static Document Doc
        {
            get { return Application.DocumentManager.MdiActiveDocument; }
        }
        [CommandMethod("SWJX_AddMenu")]
        public static void AddMenu()
        {
            //获取到ACAD.cuix
            CustomizationSection cs = new CustomizationSection((string)Application.GetSystemVariable("MENUNAME"));
            string strCurWorkspace = (string)Application.GetSystemVariable("WSCURRENT");
            try
            {
                string customName = "四维聚象",customId = "ID_siweijuxiang";
                //workspace的操作
                Workspace curWorkspace = cs.getWorkspace(strCurWorkspace);
                MacroGroup maGroup = null;
                if (!cs.MenuGroup.MacroGroups.Contains(customName))
                {
                    maGroup = new MacroGroup(customName, cs.MenuGroup);
                }
                else
                {
                    foreach (MacroGroup mp in cs.MenuGroup.MacroGroups)
                        if (mp.Name == customName)
                            maGroup = mp;
                }
                //清除宏
                maGroup.MenuMacros.Clear();

                //查找tab
                RibbonTabSource myRibbonTab = null;
                foreach (RibbonTabSource ribTab in cs.MenuGroup.RibbonRoot.RibbonTabSources)
                    if (ribTab.Name == customName)
                        myRibbonTab = ribTab;

                if (myRibbonTab == null)
                {
                    myRibbonTab = new RibbonTabSource(cs.MenuGroup.RibbonRoot);
                    myRibbonTab.Text = myRibbonTab.Name = customName;
                    myRibbonTab.Id = customId;
                    cs.MenuGroup.RibbonRoot.RibbonTabSources.Add(myRibbonTab);
                }

                Autodesk.AutoCAD.Customization.RibbonPanelSource panelSrc = null;
                foreach (Autodesk.AutoCAD.Customization.RibbonPanelSource ribPanel in cs.MenuGroup.RibbonRoot.RibbonPanelSources)
                    if (ribPanel.Name == customName)
                        panelSrc = ribPanel;
                if (panelSrc == null)
                {
                    panelSrc = new Autodesk.AutoCAD.Customization.RibbonPanelSource(cs.MenuGroup.RibbonRoot);
                    panelSrc.Text = panelSrc.Name = customName;
                    panelSrc.Id = customId;
                    cs.MenuGroup.RibbonRoot.RibbonPanelSources.Add(panelSrc);

                    RibbonRow row = new RibbonRow();
                    panelSrc.Items.Add((Autodesk.AutoCAD.Customization.RibbonItem)row);

                    Autodesk.AutoCAD.Customization.RibbonCommandButton button1 = new Autodesk.AutoCAD.Customization.RibbonCommandButton(row);
                    button1.Text = "登陆";
                    MenuMacro menuMac1 = maGroup.CreateMenuMacro("login_Macro", "SWJX_Login", "login_Tag", "login_Help",
                                        MacroType.Any, "Image//login_logo.ico", "Image//login_logo.ico", "siweijuxiang_login");
                    button1.MacroID = menuMac1.ElementID;
                    button1.ButtonStyle = RibbonButtonStyle.LargeWithText;
                    row.Items.Add((Autodesk.AutoCAD.Customization.RibbonItem)button1);

                    RibbonPanelSourceReference ribPanelSourceRef = new RibbonPanelSourceReference(myRibbonTab);
                    ribPanelSourceRef.PanelId = panelSrc.ElementID;
                    myRibbonTab.Items.Add(ribPanelSourceRef);
                }

                //添加菜单
                PopMenu pmParent = cs.MenuGroup.PopMenus.FindPopWithName(customName);
                if (pmParent == null)
                    pmParent = new PopMenu(customName, new StringCollection() { "POP14" }, "PMU_191_D624B", cs.MenuGroup);
                //清除菜单
                pmParent.PopMenuItems.Clear();
                new PopMenuItem(new MenuMacro(maGroup, "账户登陆", "SWJX_Login", ""), "登陆", pmParent, -1);
                new PopMenuItem(new MenuMacro(maGroup, "注销账户", "SWJX_ChangeUser", ""), "注销", pmParent, -1);
                new PopMenuItem(new MenuMacro(maGroup, "导出户型数据", "SWJX_ExportBSPXml", ""), "导出户型数据", pmParent, -1);
                new PopMenuItem(new MenuMacro(maGroup, "创建默认图层", "SWJX_CreateDefaultLayer", ""), "创建默认图层", pmParent, -1);
                new PopMenuItem(new MenuMacro(maGroup, "四维聚象工作平台", "SWJX_WorkSpace", ""), "四维聚象工作平台", pmParent, -1);
                cs.MenuGroup.PopMenus.Add(pmParent);

                //添加到工作区
                foreach (Workspace wk in cs.Workspaces)
                {
                    bool bFound = false;
                    foreach(WorkspacePopMenu pm in wk.WorkspacePopMenus)
                    {
                        if (pm.PopMenuID == pmParent.ElementID)
                            bFound = true;
                    }
                    if (!bFound)
                    {
                        WorkspacePopMenu wkp = new WorkspacePopMenu(wk, pmParent) { Display=1};
                    }
                    bFound = false;
                    foreach (WSRibbonTabSourceReference pm in wk.WorkspaceRibbonRoot.WorkspaceTabs)
                    {
                        if (pm.TabId == myRibbonTab.ElementID)
                            bFound = true;
                    }
                    if (!bFound)
                    {
                        wk.WorkspaceRibbonRoot.WorkspaceTabs.Add(new WSRibbonTabSourceReference() { TabId = myRibbonTab.ElementID,Show=true, IsActive=true,TabSource=myRibbonTab });
                    }
                }
                if (cs.IsModified) cs.Save();
            }
            finally
            {
                //命令行手动加载
                //Application.SetSystemVariable("FILEDIA", 0);
                //Application.DocumentManager.MdiActiveDocument.SendStringToExecute("cuiunload " + cs.CUIFileBaseName + " ", false, false, false);
                //Application.DocumentManager.MdiActiveDocument.SendStringToExecute("cuiload " + cs.CUIFileBaseName + " filedia 1 ", false, false, false);
                Application.ReloadAllMenus();
            }
        }
        [CommandMethod("SWJX_ExportBSPXml")]
        public static void ExportBSPXml()
        {
            if (LoginInfo.instance().isLogin)
            {
                PromptSaveFileOptions saveOption = new PromptSaveFileOptions("") { InitialFileName = "户型数据.xml", InitialDirectory = Directory.GetLogicalDrives().Last() };
                PromptFileNameResult ppf = Doc.Editor.GetFileNameForSave(saveOption);
                string strFilePath = ppf.StringResult;
                if (ppf.Status == PromptStatus.OK && !string.IsNullOrEmpty(strFilePath))
                    ExportFile(strFilePath);
            }
            else
            {
                Login("ExportBSPXml");//登陆页面
            }
        }
        //laydel
        [CommandMethod("SWJX_CreateDefaultLayer")]
        public static void CreateDefaultLayer()
        {
            if (LoginInfo.instance().isLogin)
            {//创建图层
                Autodesk.AutoCAD.ApplicationServices.DocumentLock m_DocumentLock = Doc.LockDocument();
                using (Autodesk.AutoCAD.DatabaseServices.Transaction trans = Doc.Database.TransactionManager.StartTransaction())
                {    //以读的方式打开图层表
                    Random rdColor = new Random();
                    Autodesk.AutoCAD.DatabaseServices.LayerTable acLyrTbl = trans.GetObject(Doc.Database.LayerTableId, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead) as Autodesk.AutoCAD.DatabaseServices.LayerTable;
                    for (int i=0;i<LayerName.instance().ItemCount;i++)
                    {
                        if (acLyrTbl.Has(LayerName.instance()[i]) == false)
                        {
                            using (Autodesk.AutoCAD.DatabaseServices.LayerTableRecord acLyrTblRec = new Autodesk.AutoCAD.DatabaseServices.LayerTableRecord())
                            {
                                acLyrTblRec.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, (short)(rdColor.Next(22) * 10 + 10));// 指定图层颜色
                                acLyrTblRec.Name = LayerName.instance()[i];// 指定图层名称
                                acLyrTbl.UpgradeOpen();//修改图层打开方式为写
                                acLyrTbl.Add(acLyrTblRec);//将新图层追加到图层表
                                trans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                                acLyrTbl.DowngradeOpen();
                            }
                        }
                    }
                    //切换图层
                    Doc.Database.SetLayer("墙");
                    trans.Commit();
                }
                m_DocumentLock.Dispose();
            }
            else
            {
                Login("CreateDefaultLayer");//登陆页面
            }
        }
        public static bool ExportFile(string strFilePath)
        {
            try
            {
                string strOut = "";
                using (Transaction ts = Doc.Database.TransactionManager.StartTransaction())
                {
                    House houseModel = new House();
                    s_Pmeter.Start("正在导出请稍后......");
                    //图层处理
                    LayerTableConvert(ts, houseModel, ref strOut);
                    BlockTableConvert(ts, houseModel, ref strOut);
                    //检查点和线
                    houseModel.AjustLineAndPoint();
                    //完成进度
                    s_Pmeter.MeterProgress();
                    //导出xml
                    houseModel.XmlSerialize().Save(strFilePath);
                    System.Diagnostics.Trace.WriteLine(strOut);
                    //修改文件内容，非标准xml中以数字开头
                    //string sContent = File.ReadAllText(strFilePath, Encoding.UTF8);
                    //File.WriteAllText(strFilePath, Regex.Replace(sContent, @"(?<=</?)_(?=\d+\s?/?>)", ""));
                    s_Pmeter.Stop();
                }
                return true;
            }
            catch (System.Exception ex)
            {//异常
                s_Pmeter.Stop();
                DwgConvert.PutMessage("Exception:" + ex.Message);
                return false;
            }
        }
        private static void LayerTableConvert(Transaction ts, House house, ref string strOut)
        {
            LayerTable layTbl = ts.GetObject(Doc.Database.LayerTableId, OpenMode.ForRead) as LayerTable;
            foreach (ObjectId oidlyer in layTbl)
            {
                LayerTableRecord layer = ts.GetObject(oidlyer, OpenMode.ForRead) as LayerTableRecord;
                if(!house.Dict.Keys.Contains(layer.Name.Trim())&& layer.Name!="0")
                    DwgConvert.PutMessage("配置文件中在不到图层:" + layer.Name);
            }
        }
        private static void BlockTableConvert(Transaction ts, House house, ref string strOut)
        {
            Dictionary<string, List<Entity>> sortDataDic = new Dictionary<string, List<Entity>>();
            BlockTable blkTbl = ts.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
            //获取单位
            BspObject.s_unitValue = (ts.GetObject(blkTbl[BlockTableRecord.PaperSpace], OpenMode.ForRead) as BlockTableRecord).Units;
            foreach (ObjectId oidrd in blkTbl)
            {
                BlockTableRecord modelSpace = ts.GetObject(oidrd, OpenMode.ForRead) as BlockTableRecord;
                foreach (ObjectId oidblk in modelSpace)
                {
                    DBObject dbobj = ts.GetObject(oidblk, OpenMode.ForRead);
                    if (dbobj is Entity)
                    {
                        Entity entity = dbobj as Entity;
                        if (!sortDataDic.Keys.Contains(entity.Layer.Trim()))
                            sortDataDic.Add(entity.Layer.Trim(), new List<Entity> { entity });
                        else
                            sortDataDic[entity.Layer.Trim()].Add(entity);
                    }
                    else
                    {
                        DwgConvert.PutMessage("Oid: {0}", oidblk);
                    }
                }
            }
            //打印数据
            foreach (KeyValuePair<string, List<Entity>> item in sortDataDic)
            {
                string dataType = "";
                foreach (Entity it in item.Value)
                {
                    if (dataType.Split(new char[] { ',' }).Where(o => o == it.GetType().Name).Count() == 0)
                        dataType += it.GetType().Name + ",";
                }
                System.Diagnostics.Trace.WriteLine(item.Key + ":" + dataType);
            }

            //显示进度
            s_Pmeter.SetLimit(sortDataDic.Count+1);
            //AlignedDimension最后处理
            foreach (KeyValuePair<string, List<Entity>> item in sortDataDic)
            {
                if (house.Dict.Keys.Contains(item.Key.Trim()))
                    foreach (Entity entity in item.Value)
                        house.AddData(entity);
                s_Pmeter.MeterProgress();
            }
        }
        [CommandMethod("SWJX_WorkSpace")]
        public static void PaletteSetPopOut()
        {
            if (LoginInfo.instance().isLogin)
            {
                if (s_Ps == null)
                {
                    string paletteName = "四维聚象" + (string.IsNullOrEmpty(LoginInfo.instance().userName) ?
                        "" : "(" + LoginInfo.instance().userName + ")");
                    s_Ps = new PaletteSet(paletteName);
                    PaletteControl pCtrl = new PaletteControl();
                    s_Ps.Add("Palette1", pCtrl);
                    s_Ps.Visible = true;
                }
                else
                {
                    s_Ps.Visible = true;
                    if (s_Ps.AutoRollUp)
                        s_Ps.AutoRollUp = false;
                }
            }
            else
            {
                //登陆页面
                Login("PaletteSetPopOut");
            }
        }
        [CommandMethod("CreateText")]
        public static void CreateText()
        {
            DocumentLock dl = Doc.LockDocument();
            try
            {
                using (Transaction tr = Doc.Database.TransactionManager.StartTransaction())
                {
                    BlockTable blockTbl = tr.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockTableRecord modelSpace = tr.GetObject(blockTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    PromptPointOptions ppt = new PromptPointOptions("\n标记位置: ") { AllowNone = true };
                    PromptPointResult ppr = Doc.Editor.GetPoint(ppt);
                    if (ppr.Status != PromptStatus.OK) return;
                    PromptStringOptions ppsType = new PromptStringOptions("\n房间或者区域名称: ");
                    PromptResult pprType = Doc.Editor.GetString(ppsType);
                    if (pprType.Status != PromptStatus.OK) return;

                    Doc.Database.SetLayer(LayerName.instance()[1]);
                    DBText mt = new DBText();
                    mt.TextString = pprType.StringResult;
                    mt.Height = 100;
                    mt.Position = ppr.Value;
                    modelSpace.AppendEntity(mt);
                    tr.AddNewlyCreatedDBObject(mt, true);
                    tr.Commit();
                }
            }
            catch(System.Exception ex)
            {
                PutMessage(ex.Message);
            }
            dl.Dispose();
        }
        [CommandMethod("SWJX_Login")]
        public static void Login(string sCommand)
        {
            if (LoginInfo.instance().ParseFile())
            {//自动登陆
                if (LoginInfo.instance().AutoLogin())
                {
                    if (sCommand == "ExportBSPXml")
                        ExportBSPXml();
                    else if (sCommand == "CreateDefaultLayer")
                        CreateDefaultLayer();
                    else
                        PaletteSetPopOut();//显示任务窗口    
                    return;
                }
            }

            LoginControl lg = new LoginControl(sCommand);
            lg.ShowDialog();
        }
        [CommandMethod("SWJX_Logout")]
        public static void Logout()
        {
            if (LoginInfo.instance().isLogin)
            {
                HttpManager.UserLogout();
                LoginInfo.instance().isLogin = false;
                if (s_Ps != null)
                {
                    if (s_Ps.Visible)
                        s_Ps.Visible = false;
                    s_Ps.Close();
                    s_Ps.Dispose();
                    s_Ps = null;
                }
            }
        }
        [CommandMethod("SWJX_ChangeUser")]
        public static void ChangeUser()
        {
            try
            {
                Logout();
                File.Delete(LoginInfo.instance().globalfileName);
            }
            catch(System.Exception ex)
            {
                PutMessage(ex.Message);
            }
        }
        [CommandMethod("SWJX_InsertBlockReference")]
        public static void InsertBlockReference()
        {
            DocumentLock m_DocumentLock = Doc.LockDocument();
            using (Transaction trans = Doc.Database.TransactionManager.StartTransaction())
            {
                try
                {
                    if (DwgItem.s_bCommandEnd == true)
                    {
                        DwgItem.s_bCommandEnd = false;
                        PromptPointOptions ppt = new PromptPointOptions("\n图块位置: ") { AllowNone = true };
                        PromptPointResult ppr = Doc.Editor.GetPoint(ppt);
                        if (ppr.Status != PromptStatus.OK)
                        {
                            //当前选中的数据置空
                            DwgItem.s_CurrentDwgFile = "";
                            DwgItem.s_bCommandEnd = true;
                            return;
                        }
                        //PromptKeywordOptions ppk = new PromptKeywordOptions("\n创建新的块参照");
                        //ppk.Keywords.Add("Yes", "Yes", "是(Y)", true, true);
                        //ppk.Keywords.Add("No", "No", "否(N)", true, true);
                        //PromptResult ppret = Doc.Editor.GetKeywords(ppk);
                        //if (ppret.Status != PromptStatus.OK)
                        //{
                        //    //当前选中的数据置空
                        //    DwgItem.m_CurrentDwgFile = "";
                        //    DwgItem.m_bCommandEnd = true;
                        //    return;
                        //}
                        Autodesk.AutoCAD.Geometry.Point3d pt = ppr.Value;
                        //切换图层
                        Doc.Database.SetLayer(s_DmCtrl.m_TabName=="门窗"?"硬装":s_DmCtrl.m_TabName);
                        // 写块数据
                        //string strBlockName = ppret.StringResult == "Yes" ? s_DmCtrl.m_CurrentDwgAttrib["图例编码"] + "(" + DateTime.Now.Ticks + ")" : s_DmCtrl.m_CurrentDwgAttrib["图例编码"];
                        string strBlockName = DwgItem.s_CurrentDwgAttrib["图例编码"] + "(" + DateTime.Now.Ticks + ")";
                        BlockTable bt = trans.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
                        BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                        BlockReference br = btr.ImportOuterFileBlock(pt, DwgItem.s_CurrentDwgFile, strBlockName);
                        btr.AddAttributeToBlockTableRecord(br, DwgItem.s_CurrentDwgAttrib);//添加属性
                        trans.Commit();

                        //当前选中的数据置空
                        DwgItem.s_CurrentDwgFile = "";
                        DwgItem.s_bCommandEnd = true;
                    }
                }
                catch (System.Exception ex)
                {
                    trans.Abort();
                    //当前选中的数据置空
                    DwgItem.s_CurrentDwgFile = "";
                    DwgItem.s_bCommandEnd = true;
                    PutMessage(ex.Message);
                }
            }
            m_DocumentLock.Dispose();
        }
        #region 参考代码
        //[CommandMethod("SWJX_UpdateBlockAttribute")]
        public static void UpdateBlockAttribute()
        {
            using (Transaction trans = Doc.Database.TransactionManager.StartTransaction())
            {
                PromptEntityOptions ppe = new PromptEntityOptions("\nget selection entity: ");
                PromptEntityResult ppr = Doc.Editor.GetEntity(ppe);
                if (ppr.Status != PromptStatus.OK) return;
                BlockReference blkRef = trans.GetObject(ppr.ObjectId, OpenMode.ForRead) as BlockReference;
                BlockTableRecord blkRec = trans.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
                PromptStringOptions ppsType = new PromptStringOptions("\nget block sn: ");
                PromptResult pprType = Doc.Editor.GetString(ppsType);
                if (pprType.Status != PromptStatus.OK) return;

                DwgItem.s_CurrentDwgAttrib.Clear();
                DwgItem.s_CurrentDwgAttrib.Add("图例编码", pprType.StringResult);
                DwgItem.SetObjectAttribute(pprType.StringResult);
                blkRec.AddAttributeToBlockTableRecord(blkRef,DwgItem.s_CurrentDwgAttrib);
                trans.Commit();
            }
        }
        public static void PolyLineToLine()
        {
            //Autodesk.AutoCAD.Geometry.Point3dCollection col_point = new Autodesk.AutoCAD.Geometry.Point3dCollection();
            //Line ent_line = item as Line;
            //Point3d startPoint = ent_line.StartPoint;
            //Point3d endPoint = ent_line.EndPoint;
            //col_point.Add(startPoint);
            //col_point.Add(endPoint);

            //Polyline poly = new Polyline();

            //poly.Color = reg.Color;
            //poly.Closed = true;
            //poly.LineWeight = reg.LineWeight;
            //poly.LinetypeId = reg.LinetypeId;
            //PolylineTools.CreatePolyline(poly, col_point);

            //btr.AppendEntity(poly);
            //trans.AddNewlyCreatedDBObject(poly, true);
        }
#endregion
        [CommandMethod("SWJX_ChangeConfig")]
        public static void SWJX_ChangeConfig()
        {
            try
            {
                PromptStringOptions ppsType = new PromptStringOptions("\n设置Dm地址(D)文件上传地址(U)文件存储地址(S): ");
                PromptResult pprType = Doc.Editor.GetString(ppsType);
                if (string.Compare(pprType.StringResult, "D", true) == 0)
                {
                    PromptStringOptions ppsDm = new PromptStringOptions("\n设置Dm地址: ") { DefaultValue = HttpManager.s_homeurl };
                    PromptResult pprDm = Doc.Editor.GetString(ppsDm);
                    if (pprDm.Status == PromptStatus.OK)
                    {
                        HttpManager.s_homeurl = pprDm.StringResult;
                        (Properties.Settings.Default["后台地址"] as StringCollection)[0] = pprDm.StringResult;
                        Properties.Settings.Default.Save();
                    }
                }
                else if (string.Compare(pprType.StringResult, "U", true) == 0)
                {
                    PromptStringOptions ppsUpload = new PromptStringOptions("\n设置文件上传地址: ") { DefaultValue = HttpManager.s_fileupload };
                    PromptResult pprUpload = Doc.Editor.GetString(ppsUpload);
                    if (pprUpload.Status == PromptStatus.OK)
                    {
                        HttpManager.s_fileupload = pprUpload.StringResult;
                        (Properties.Settings.Default["上传地址"] as StringCollection)[0] = pprUpload.StringResult;
                        Properties.Settings.Default.Save();
                    }
                }
                else if (string.Compare(pprType.StringResult, "S", true) == 0)
                {
                    PromptStringOptions ppsFileStore = new PromptStringOptions("\n设置文件存储地址: ") { DefaultValue = HttpManager.s_filestore };
                    PromptResult pprFileStore = Doc.Editor.GetString(ppsFileStore);
                    if (pprFileStore.Status == PromptStatus.OK)
                    {
                        HttpManager.s_filestore = pprFileStore.StringResult;
                        (Properties.Settings.Default["下载地址"] as StringCollection)[0] = pprFileStore.StringResult;
                        Properties.Settings.Default.Save();
                    }
                }
            }
            catch(System.Exception ex)
            {
                PutMessage(ex.Message);
            }
        }
        public static void Cancel()
        {
            //Doc.SendStringToExecute(" ", true, false, true);
            Doc.SendStringToExecute("\x03", false, false, false);
        }
        public static void PutMessage(string content,params object[] parameter)
        {
            Doc.Editor.WriteMessage(content+"\n", parameter);
        }
    }
}
